package com.treasure.mall.zbqmallmanager.controller.contact;

import com.alibaba.fastjson.JSON;
import com.treasure.mall.biz.base.UserDetails;
import com.treasure.mall.biz.dto.common.ChatMessageBodyDTO;
import com.treasure.mall.biz.dto.condition.ContactHistoryMessageCondition;
import com.treasure.mall.biz.entity.contact.ChatPO;
import com.treasure.mall.biz.entity.contact.ContactHistoryMessagePO;
import com.treasure.mall.biz.entity.user.MerchantPO;
import com.treasure.mall.biz.entity.user.UserPO;
import com.treasure.mall.biz.mapstruct.ContactMapStruct;
import com.treasure.mall.biz.remote.live.TencentIMService;
import com.treasure.mall.biz.remote.live.enums.MessageType;
import com.treasure.mall.biz.service.core.contact.ChatService;
import com.treasure.mall.biz.service.core.contact.ContactHistoryMessageService;
import com.treasure.mall.biz.service.core.user.MerchantService;
import com.treasure.mall.biz.service.core.user.UserService;
import com.treasure.mall.zbq.common.base.ApiResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * <p>
 * +---------------------------------------------------------
 * * @package: com.treasure.mall.zbqmallmanager.controller.contact
 * * @author: guomw (guomwchen@foxmail.com)
 * * @date: 2020/8/12 2:01 下午
 * * @since: V1.0.0
 * +---------------------------------------------------------
 * 注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的
 *
 */
@Controller
@RequestMapping("/contact")
public class ContactController {

    @Autowired
    private ChatService chatService;
    @Autowired
    private ContactHistoryMessageService messageService;
    @Autowired
    private UserService userService;
    @Autowired
    private MerchantService merchantService;
    @Autowired
    private TencentIMService imService;

    @RequestMapping("/chat")
    @PreAuthorize("hasRole('MERCHANT')")
    public String home(Model model, @AuthenticationPrincipal UserDetails userDetails) {
        MerchantPO po = merchantService.findById(userDetails.getId());
        model.addAttribute("merchantId", userDetails.getId());
        model.addAttribute("merchantUserId", po.getUser().getUserId());
        return "contact/index";
    }

    /**
     * 获取聊天列表
     *
     * @param userDetails
     * @return
     */
    @PostMapping("/chat/list")
    @ResponseBody
    public ApiResult chatList(@AuthenticationPrincipal UserDetails userDetails) {
        List<ChatPO> list = chatService.findAll(userDetails.getId());
        return ApiResult.ok(ContactMapStruct.INSTANCE.pos2vos(list));
    }

    /**
     * 添加客服回复历史消息
     *
     * @return
     */
    @PostMapping("/history/add")
    @ResponseBody
    public ApiResult addHistoryMessage(@AuthenticationPrincipal UserDetails userDetails,
                                       @RequestParam Long userId,
                                       @RequestParam String groupId,
                                       @RequestParam String message,
                                       @RequestParam(required = false, defaultValue = "general") String type
    ) {
        UserPO user = userService.findById(userId);
        MerchantPO merchantPO = merchantService.findById(userDetails.getId());
        if (user == null || merchantPO == null) {
            return ApiResult.error("参数错误");
        }
        ChatMessageBodyDTO dto = new ChatMessageBodyDTO();
        dto.setGroupId(groupId);
        dto.setMessage(message);
        dto.setLevel(null);
        dto.setName(merchantPO.getData().getTitle());
        if (StringUtils.isNotBlank(type)) {
            dto.setType(type);
        } else {
            dto.setType(MessageType.general.getDesc());
        }
        //商家所属用户ID
        dto.setUserId(merchantPO.getUser().getUserId());
        dto.setFace(merchantPO.getUser().getAvatar());
        dto.setTime(LocalDateTime.now());
        messageService.save(user, merchantPO.getMerchantId(), dto);
        //发送聊天消息
        imService.sendChatMessage(dto);

        //更新回复消息
        chatService.modifyLastMessageByMerchantId(user.getUserId(), merchantPO.getMerchantId(), dto.getMessage());

        return ApiResult.ok();
    }

    /**
     * 获取历史消息日志
     *
     * @return
     */
    @GetMapping("/history/message")
    @ResponseBody
    public ApiResult getLiveHistoryMessage(@AuthenticationPrincipal UserDetails userDetails,
                                           @RequestParam Long userId,
                                           @RequestParam(required = false, defaultValue = "1") Integer page,
                                           @RequestParam(required = false, defaultValue = "20") Integer size
    ) {
        UserPO user = userService.findById(userId);
        MerchantPO merchantPO = merchantService.findById(userDetails.getId());
        if (user == null || merchantPO == null) {
            return ApiResult.error("参数错误");
        }

        ContactHistoryMessageCondition condition = new ContactHistoryMessageCondition();
        condition.setMerchantId(merchantPO.getMerchantId());
        condition.setUserId(user.getUserId());
        Page<ContactHistoryMessagePO> pages = messageService.findAll(page, size, condition);
        List<ChatMessageBodyDTO> list = new ArrayList<>();
        pages.getContent().forEach(item -> {
            if (StringUtils.isNotBlank(item.getMessageBody())) {
                ChatMessageBodyDTO messageBody = JSON.parseObject(item.getMessageBody(), ChatMessageBodyDTO.class);
                list.add(messageBody);
            }
        });
        chatService.resetNoReadCount(userId, merchantPO.getMerchantId());

        return ApiResult.ok(list);
    }

}
